package cn.lijigou.shopping.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class LoadImageAysnc {

	//图片缓存软引用
	private HashMap<String, SoftReference<Drawable>> imageCache;
	//线程池
	private BlockingQueue<Runnable> queue;
	private ThreadPoolExecutor executor;
	
	public LoadImageAysnc(Context context) {
		imageCache = new HashMap<String, SoftReference<Drawable>>();
		queue = new LinkedBlockingQueue<Runnable>();
		executor = new ThreadPoolExecutor(3, 15, 180, TimeUnit.SECONDS, queue);
		
	}

	//异步加载图片的方法（其实可以以任何形式得到图片）
	public Drawable loadImage(final int position, final String id, final String iconSrc, final String type, final ImageCallBack imageCallBack)
	{
	
		//如果有缓存则使用缓存中的图片
		if(imageCache.containsKey(id)){
			SoftReference<Drawable> softReference = imageCache.get(id);
			Drawable drawable = softReference.get();
			if(drawable != null) {
//				imageCallBack.imageLoaded(drawable, position);
				return drawable;
			}
		}
		//图片加载完成
		final Handler handler = new Handler()
		{
			
			public void handleMessage(Message msg) {
				Drawable drawable = (Drawable) msg.obj;
				//图片加载完成的回调函数，用于更新imageview
				imageCallBack.imageLoaded(drawable, position);
			}
		};
		
		//异步图片下载方法
		executor.execute(
				new Runnable() {
					
					
					public void run() {
						Drawable drawable = null;
						String filePath = "/sdcard/tuangou/"+id+type;
						File file=new File(filePath);
						if(file.exists()){
							try{
								drawable=Drawable.createFromPath(filePath);
								imageCache.put(id, new SoftReference<Drawable>(drawable));
								Message msg = handler.obtainMessage(0, drawable);
								msg.sendToTarget();
							}catch (Exception e) {
								e.printStackTrace();
							}
						}else {
							new Thread() {
								
								public void run() {
									InputStream is = null;
									Drawable drawable = null;
//									if(getNetConnectState(context)){
										try {
											HttpURLConnection conn = Util.getHttpURLConnection(iconSrc);
											conn.setDoInput(true);
											if (conn.getResponseCode() == 200) {
												is = conn.getInputStream();
												int size=conn.getContentLength();
												if (is != null) {
													Bitmap bitmap = BitmapFactory.decodeStream(is);
													drawable = new BitmapDrawable(bitmap);
													 
													if(drawable!=null&&size>4){
														imageCache.put(id, new SoftReference<Drawable>(drawable));
														Message msg = handler.obtainMessage(0, drawable);
														msg.sendToTarget();
														try{
															String filePath = "/sdcard/tuangou/"+id+type;
															saveBitMap(bitmap, filePath);
														}catch (Exception e) {
															e.printStackTrace();
														}
													 }
											    	}
												}
										}catch (Exception e1) {
											e1.printStackTrace();
										}
//									}
									
								 }
								private void saveBitMap(Bitmap bitmap, String filePath)
							    throws IOException, FileNotFoundException {
									File fp = new File("/sdcard/tuangou");
									File file = new File("/sdcard/tuangou/.nomedia");
									if (!fp.exists()) {
										fp.mkdir();
										if((!file.exists())){  
											file.createNewFile();
										}
									}else{
										File f = new File(filePath);
										f.createNewFile();
										FileOutputStream fos = new FileOutputStream(f);
										bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
										fos.flush();
										fos.close();
									}
									}
								}.start();
								 
							// TODO: handle exception
						}
					}
				});
		return null;
	}
	
 
	
	//回调接口
	public interface ImageCallBack
	{
		public void imageLoaded(Drawable drawable, int position);
	}
}























